<?php
class ZendX_Config_Manager {
	protected $_config = NULL;
	protected $_baseDir = NULL;
	protected $_container = array();
	protected static $_instance = NULL;

	/**
	 * @param string resource name
	 * @throws Zend_Exception
	 * @return Zend_Config
	 */
	public function getConfig($name, $env = NULL) {
		$env = ($env === NULl) ? APPLICATION_ENV : $env;
		if(!isset($this->_container[$name])) {
			if(!isset($this->_config->$name)) {
				throw new Zend_Exception("Can\'t find configuration for $name");
			}
			$conf = $this->_config->$name;
			if($conf->cache) {
				$cache = Zend_Registry::get('Zend_Cache');
				if(FALSE === ($this->_container[$name] = $cache->load("applicationConfigManager$name"))) {
					$this->_container[$name] = ZendX_Config::factory("{$this->_baseDir}/{$conf->path}", $env);
					$cache->save($this->_container[$name], "applicationConfigManager$name");
				}
			} else {
				$this->_container[$name] = ZendX_Config::factory("{$this->_baseDir}/{$conf->path}", $env);
			}
		}
		return $this->_container[$name];
	}

	protected function __construct() {
		$cache = Zend_Registry::get('Zend_Cache');
		$this->_container['application'] = Zend_Registry::get('Application_Config');
		$this->_baseDir = $this->_container['application']->configManager->configDir;

		if($this->_container['application']->configManager->cache) {
			if(FALSE === ($this->_config = $cache->load('applicationConfigManager'))) {
				$this->_config = ZendX_Config::factory($this->_container['application']->configManager->path, APPLICATION_ENV);
				$cache->save($this->_config, 'applicationConfigManager');
			}
		} else {
			$this->_config = ZendX_Config::factory($this->_container['application']->configManager->path, APPLICATION_ENV);
		}
	}

	/**
	 * @return ZendX_Config_Manager
	 */
	static public function getInstance() {
		if(NULL === self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	public function __clone() {}
}